<template>
  <div>
    <el-button type="primary" plain @click="dialogFormVisible = true">添加订单</el-button>
    <el-table :data="orders" style="width: 100%">
      <el-table-column label="编号" prop="id" />
      <el-table-column label="商品ID" prop="productId" />
      <el-table-column label="商品名称" prop="product.name" />
      <el-table-column label="数量" prop="count" />
      <el-table-column label="日期" prop="date" />
      <el-table-column align="right">
        <template #header>
          <el-input v-model="keyword" size="small" placeholder="搜索订单" @change="loadOrder(current)" />
        </template>
        <template #default="scope">
          <el-button size="small" @click="editOrder(scope.row)">更新</el-button>
          <el-button size="small" type="danger" @click="deleteOrder(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize" @current-change="loadOrder" />
    <!-- 对话框 -->
    <el-dialog v-model="dialogFormVisible" title="订单信息" width="500" @close="order = {}">
      <el-form :model="order">
        <el-form-item label="商品ID">
          <el-input v-model="order.productId" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="order.product.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="order.count" autocomplete="off" />
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker v-model="order.date" type="date" placeholder="选择日期" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="saveOrder">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  name: 'OrderView',
  data() {
    return {
      orders: [], // 订单集合
      keyword: '', // 搜索关键词
      current: 1, // 当前页
      pageSize: 10, // 页大小
      total: 0, // 总数
      dialogFormVisible: false, // 对话框是否显示
      order: {}, // 订单信息
    };
  },
  methods: {
    // 加载订单
    // Update the error handling in loadOrder method
    loadOrder(current) {
      this.current = current;
      this.$axios.get('/api/orders-page', {
        params: {
          current: this.current,
          pageSize: this.pageSize,
          keyword: this.keyword
        },
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
      })
          .then((result) => {
            this.orders = result.data.data;
            this.total = result.data.total;
          })
          .catch((error) => {
            console.error('加载订单失败:', error);
            if (error.response?.status === 401) {
              // Token 过期，跳转到登录页
              this.$router.push('/login');
            }
          });

    },
    // 编辑订单
    editOrder(order) {
      this.dialogFormVisible = true;
      this.order = JSON.parse(JSON.stringify(order));
    },
    // 保存订单
    saveOrder() {
      if (this.order.id) {
        // 更新订单
        this.$axios
            .put('/api/order', this.order)
            .then((result) => {
              if (result.data === 'OK') {
                ElMessage.success('更新成功');
                this.loadOrder(this.current);
              }
            })
            .catch((error) => {
              console.error('更新订单失败:', error);
            });
      } else {
        // 添加订单
        this.$axios
            .post('/api/order', this.order)
            .then((result) => {
              if (result.data === 'OK') {
                ElMessage.success('添加成功');
                this.loadOrder(this.current);
              }
            })
            .catch((error) => {
              console.error('添加订单失败:', error);
            });
      }
      this.dialogFormVisible = false;
    },
    // 删除订单
    deleteOrder(id) {
      ElMessageBox.confirm('是否确认删除?', 'Warning', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(() => {
            this.$axios
                .delete('/api/order/' + id)
                .then((result) => {
                  if (result.data === 'OK') {
                    this.loadOrder(this.current);
                  }
                })
                .catch((error) => {
                  console.error('删除订单失败:', error);
                });
          })
          .catch(() => {});
    },
  },
  mounted() {
    // 默认加载第一页
    this.loadOrder(1);
  },

};
</script>

<style scoped>
</style>
